package com.example.myapplication;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.provider.MediaStore;

import java.util.Timer;
import java.util.TimerTask;

public class MusicService extends Service {

    private MediaPlayer mediaPlayer;
    private Timer timer;

    public MusicService() {

    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MusicControl();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer = new MediaPlayer();   //创建播放器对象
    }

    public void addTimer() {   //添加计时器用于设置音乐播放器中的播放进度条

        if (timer == null) {
            timer = new Timer();
            TimerTask task = new TimerTask() {   //创建计时器对象
                @Override
                public void run() {
                    if (mediaPlayer == null) {
                        return;
                    }
                    int duration = mediaPlayer.getDuration();

                    //获取播放进展
                    int currentPosition = mediaPlayer.getCurrentPosition();

                    //创建消息对象
                    Message msg = MainActivity.handler.obtainMessage();

                    //将音乐的总时长和播放进展封装至消息对象中
                    Bundle bundle = new Bundle();
                    bundle.putInt("duration", duration);
                    bundle.putInt("currentPosition", currentPosition);

                    msg.setData(bundle);

                    MainActivity.handler.sendMessage(msg);
                }
            };

            //从开始计时任务后的第5毫米，第一次执行task任务，以后每500毫秒执行一次
            timer.schedule(task, 5, 500);
        }
    }

    class MusicControl extends Binder {
        public void play(String musicPath) {
            try {
                mediaPlayer.reset();  //重置音乐播放器
                //加载多媒体文件
                mediaPlayer.setDataSource(musicPath);


                mediaPlayer.prepare();

                mediaPlayer.start(); //播放音乐
                addTimer();  //添加计时器

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public void pausePlay() {
            mediaPlayer.pause();  //暂停播放音乐
        }

        public void continuePlay() {
            mediaPlayer.start();   //继续播放音乐
        }

        public void seekTo(int progress) {
            mediaPlayer.seekTo(progress);  //设置音乐播放的位置
        }

        public void stopMusic() {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mediaPlayer == null) {
            return;
        }

        mediaPlayer.stop();   //停止播放音乐
        mediaPlayer.release();  //释放占用的资源
        mediaPlayer = null;    //将mediaPlayer对象置为空

    }
}
